<?php

function installremove()
{
	if( isset($_POST['b_unow']) ) {
		shell_exec("nohup ../services/packman/apt_upgrade_wwwadmin >> /var/log/apt 2>> /var/log/apt &");
		info('update_started');
	}
	else if( isset($_POST['b_aptget']) && isset($_SESSION['packman']) ) {
		$installstr = '';
		foreach( $_SESSION['packman'] AS $pkgname => $pkgarr ) {
			//ej installerad, vald = installera
			if( !$pkgarr['installed'] && array_key_exists('pkgchecked'.$pkgname, $_POST) )
				$installstr .= "\"$pkgname\" ";
			//installerad, ej vald = avinstallera
			if( $pkgarr['installed'] && !$pkgarr['mandatory'] && !array_key_exists('pkgchecked'.$pkgname, $_POST) ) {
				$installstr .= "\"$pkgname-\" ";
				if( isset($pkgarr['also_remove']) ) {
					$rmarr = explode(' ', $pkgarr['also_remove']);
					foreach( $rmarr AS $rmname ) {
						$installstr .= "\"$rmname-\" ";
					}
				}
			}
		}
		if( $installstr != '' ) {
			shell_exec("nohup ../services/packman/apt_install_wwwadmin $installstr >> /var/log/apt 2>> /var/log/apt &");
			info('apt-get_started');
		}
	}
}

function upgrade()
{
	if ( !$_POST["autoupdate"]) {
		@unlink("/etc/cron.d/upgrade");
		info('saved');
	}
	else if ($_POST["hour"] && $_POST["day"]) {
		$str = "0 ".$_POST["hour"]." * * ". $_POST["day"] ." root ../services/packman/apt_upgrade_wwwadmin >> /var/log/apt 2>> /var/log/apt\n";
		file_put_contents("/etc/cron.d/upgrade",$str);
		info('saved');
	}
}

function settings()
{
	if( isset($_POST['username']) && isset($_POST['password']) ) {
		$username = $_POST['username'];
		$password = $_POST['password'];

		$apt_file = file_get_contents('/etc/apt/sources.list');
		if( $apt_file !== false ) {
			$new_apt_file = preg_replace('#(^deb\W+https://)[^:]+:[^@]+(@www\.domain\.se/repository)#m', '${1}'.$username.':'.$password.'${2}', $apt_file);
			file_put_contents('/etc/apt/sources.list', $new_apt_file);
		}
	}
}

	
////////////////////////////////////////
////////////////////////////////////////


switch( $_GET['t'] ) {
default:
case 'installremove':
	installremove();
	break;
case 'upgrade':
	upgrade();
	break;
case 'settings':
	settings();
	break;
}

?>
